import React, { useContext, useEffect, useState } from 'react'
import styles from './Cart.module.css'
import iconImg from '@/asset/bag.png'
import CartContext from '@/store/cartContext'
import CartDetail from './CartDetil/CartDetail'
import CheckOut from './CheckOut/CheckOut'


function Cart() {
    //控制购物车详情页
    const [visible, setVisible] = useState(false)
    //控制结账页
    const [showCheckOut, setShowCheckOut] = useState(false)
    const ctx = useContext(CartContext)
    //点击详情栏弹出购物车详情
    const toggleDetail = () => {
        if (ctx.totalAmount === 0) {
            setVisible(false)
            return ;
        }
        setVisible(preState=>!preState)
    }
    //点击去结算弹出结算页面
    const showCheckOutHandler = () => {
        if (ctx.totalAmount === 0) return
        setShowCheckOut(true)
    }
    //点击叉叉退出结算页面
    const hideCheckOutHandler=()=>{
        setShowCheckOut(false)
    }
    useEffect(()=>{
        if(ctx.totalAmount===0){
            setVisible(false)
            setShowCheckOut(false)
        }
    },[ctx])
    return (
        
     
         <div className={styles.Cart} onClick={toggleDetail}>
           
           {showCheckOut&& <CheckOut hideCheckOutHandler={hideCheckOutHandler}/>}
           {visible &&<CartDetail />}
           <div className={styles.Icon}>
               <img src={iconImg} alt="" />
               {ctx.totalAmount && <span className={styles.TotalAmount}>{ctx.totalAmount}</span>}
           </div>
           {ctx.totalAmount === 0 ? <p className={styles.noFood}>未选中商品</p> : <p className={styles.Price}>{ctx.totalPrice}</p>}
           <button className={`${styles.Button} ${ctx.totalAmount === 0 ? styles.Disable : null}` } onClick={ showCheckOutHandler}>去结算</button>

       </div >
    )
}

export default Cart